<template>
	<view class="content">
		<my-nav />
		<view class="list">
			<template v-for="item of data">
				<my-item :key="item.id" :data="item" />
			</template>
		</view>
	</view>
</template>
<script>
	import nav from './nav.vue'
	import item from '@/components/list-item'
	export default {
		components: {
			"my-nav": nav,
			"my-item": item
		},
		data() {
			return {
				data: [],
				page: 1,
				tab: 'all',
				isLoaded: true,
				tabClick: null,
				timer: null,
				scrollTop: 0
			}
		},
		onShow (){
			// 展示页面时，回到当前滚动条位置
			uni.pageScrollTo({
				scrollTop: this.scrollTop,
				duration: 10
			})
		},
		onLoad() {
			this.getDataList({
				tab: this.tab,
				page: this.page
			})
		},
		onPullDownRefresh() {
			// 下拉刷新数据，重置page、data
			this.data = [];
			this.page = 1;
			this.getDataList({
				tab: this.tab,
				page: this.page
			}).then(() => {
				setTimeout(() => {
					uni.stopPullDownRefresh()
				}, 1000)
			})
		},
		onReachBottom (){
			// 上拉加载数据， page自增1
			if(this.timer) {
				uni.showToast({
					title: '频繁过于操作',
					icon: 'none'
				})
				return false
			}
			// 处于加载状态，不触发再次请求
			if(!this.isLoaded) {
				return false
			}
			this.page = this.page + 1;
			this.getDataList({
				tab: this.tab,
				page: this.page
			}).then((err) => {
				if(err){
					this.page = this.page - 1
				}
			});
			this.timer = setTimeout(() => {
				this.timer = null
			}, 1000)
		},
		onTabItemTap (){
			// 模拟双击tab，回到顶部
			if (this.tabClick) { // 200ms内再次点击
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 150
				})
			}
			this.tabClick = true;
			setTimeout(() => {
				this.tabClick = false // 200ms内没有第二次点击，就当作单击
			}, 200)
		},
		onPageScroll (e){
			// 记录滚动条位置
			this.scrollTop = e.scrollTop
		},
		beforeDestroy (){
			// 销毁监听tab切换
			this.$EventBus.$off('tabBar');
			this.timer = null
		},
		mounted (){
			// 监听tab切换，重置data、tab、page值
			this.$EventBus.$on('tabBar', (res) => {
				this.data = [];
				this.tab = res;
				this.page = 1;
				this.getDataList({
					tab: this.tab,
					page: this.page
				})
			})
		},
		methods: {
			// 获取列表数据
			async getDataList (params){
				
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				this.isLoaded = false;
				
				params = params || {};
				let result = await this.$request.get('/topics', {
					tab: params.tab || 'all',
					page: params.page || 1,
					limit: 10
				});
				uni.hideLoading();
				this.isLoaded = true;
				if(result && result.success){
					this.data = this.data.concat(result.data)
				}else{
					return 'false'
				}
			}
		}
	}
</script>
<style>
	.list{
		padding-top: 40px;
	}
</style>
